<template>
  <div>
    <div v-if="isShowInfo" class="info_bg">
      <div class="info">
        <i style="font-size:104px; color: rgb(48, 159, 253);" class="el-icon-warning-outline"></i>
      </div>
      <div class="title"><span class="tips">请在微信客户端扫码打开链接</span></div>
    </div>
    <div v-else>
      <div v-if="step == 1">
        <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left"
          style="margin: 0 20px;"> 
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="dataForm.name" />
          </el-form-item>
          <el-form-item label="称谓:" prop="sex">
            <el-radio-group v-model="dataForm.sex">
              <el-radio v-for="item in sexJson" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="法人手机号:" prop="phone">
            <el-input v-model="dataForm.phone" />
          </el-form-item>
          <el-form-item label="营业执照:" prop="authImage">
            <Upload :default-image.sync="dataForm.authImage" :size="3"/>
          </el-form-item>
          <el-form-item label="公司/个体户名称:" prop="companyName">
            <el-input v-model="dataForm.companyName" />
          </el-form-item>
          <el-form-item label="在东莞工行开立公司账户:" prop="companyNo">
            <el-radio-group v-model="dataForm.companyNo">
              <el-radio v-for="item in companyNoJson" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年营收:(单位:万元)" prop="companyAmount">
            <el-input v-model="dataForm.companyAmount" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');" placeholder="请输入"/>
          </el-form-item>
          <el-form-item v-if="dataForm.type == 1" label="房产(楼盘)地址" prop="address">
            <el-input v-model="dataForm.address" />
          </el-form-item>
          <el-form-item v-if="dataForm.type == 2" label="税务等级:" prop="level">
            <el-radio-group v-model="dataForm.level">
              <el-radio v-for="item in levelJson" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="融资需求额度:(单位:万元)" prop="needAmount">
            <el-input v-model="dataForm.needAmount" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');" placeholder="请输入"/>
          </el-form-item>
          <el-checkbox v-model="xieyi" style="margin-bottom:15px">
            我已阅读并同意
            <span style="color:#409EFF" @click="openXieYi">
              《众茶国际服务协议》
            </span>
          </el-checkbox>
          <div class="btn_bg">
            <div @click="submit" :style="{'background': btnStatus ? 'rgb(24, 144, 255)' : 'gray'}" class="next_btn">{{ btnTitle }}</div>
          </div>
        </el-form>
      </div>
      <div v-if="step == 2">
        <el-form ref="phoneForm" :rules="phoneRules" :model="phoneForm" label-position="left"
          style="margin: 0 20px;">
          <el-form-item label="业务人员联系电话" prop="phone">
            <el-input v-model.trim="phoneForm.phone" :disabled="scanState == 1" placeholder="业务人员联系电话"/>
          </el-form-item>
          <el-form-item label="短信验证码(向业务人员拿取)" prop="code">
            <el-input v-model.trim="phoneForm.code" placeholder="短信验证码"/>
            <el-button type="primary" :disabled="!!time || !phoneForm.phone" style="margin-top: 15px; float: right;"
                @click="getCode()">
                {{ !time ? `获取验证码` : `重新获取(${ time }s)` }}
            </el-button>
          </el-form-item>

          <div class="btn_bg">
            <div @click="submitCode" class="next_btn">下一步</div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import { photoOcr } from '@/api/account'
  import UploadImage from '@/components/UploadImage'
  import Upload from '@/components/Upload'
  import { icbcFinanceSave, icbcFinanceSendCode, icbcFinanceCheckCode, icbcFinanceBind } from '@/api/bank'

export default {
  name: "ZcLoanSave",
  props: {

  },
  components: {
    UploadImage,
    Upload
  },
  data() {
    return {
      isShowInfo:false,
      dataForm: {
        type: 2,//1资产，2流水
        name: '',
        sex: '',
        phone: '',
        companyName: '',
        companyNo: '',
        companyAmount: '',
        address: '',
        level: '',
        needAmount: '',
        submitWay: 4,
        openId: ''
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        sex: [{ required: true, message: '请输入', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确手机号', trigger: 'change' }
        ],
        authImage: [{ required: true, message: '请输入', trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入', trigger: 'blur' }],
        companyNo: [{ required: true, message: '请输入', trigger: 'change' }],
        // companyAmount: [{ required: true, message: '请输入', trigger: 'change' }],
        address: [{ required: true, message: '请输入', trigger: 'change' }],
        level: [{ required: true, message: '请输入', trigger: 'change' }],
        // needAmount: [{ required: true, message: '请输入', trigger: 'change' }],
      },
      phoneRules: {
        phone: [{ required: true, message: '请输入', trigger: 'change' }],
        code: [{ required: true, message: '请输入', trigger: 'change' }],
      },
      sexJson: [
        { value: 1, label: '先生'},
        { value: 2, label: '女士'},
      ],
      companyNoJson: [
        { value: 1, label: '是'},
        { value: 0, label: '否'},
      ],
      levelJson: [
        { value: 'A', label: 'A'},
        { value: 'B', label: 'B'},
        { value: 'M', label: 'M'},
      ],
      step: 1,
      phoneForm: {
        phone: '',
        code: '',
        companyName: '',
        id: ''
      },
      time: 0,
			timeInterval: null,
      scanState: 1, //1:扫码，2：公众号进入
      xieyi: false,
      btnTime: 10,
      btnInterval: null,
      btnTitle: '',
      btnStatus: false
    }
  },
  computed: {

  },
  watch: {
    xieyi: {
      handler(val) {
        this.startBtnTimeGoing()
      }
    },
    'dataForm.authImage': {
      handler(val) {
        this.handleIdPic(val)
      }
    }
  },
  methods: {
    GetUrlParam(name) {
      let temp = new URL(window.location.href.replace('#/loan?', '&'))
      // 用该属性获取页面 URL 地址从问号 (?) 开始的 URL（查询部分）
      let url = temp.search;

      // 正则筛选地址栏
      var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
      // 匹配目标参数
      var result = url.substring(1).match(reg);
      //返回参数值
      return result ? decodeURIComponent(result[2]) : null;
    },
    getCode() {
      this.startGoing(300)
      icbcFinanceSendCode({
        id: this.phoneForm.id,
        phone: this.phoneForm.phone,
        companyName: this.phoneForm.companyName
      }).then(res => {
        
      })
      .catch((err) => {
        console.log(err)
      })
    },
    startGoing(val) {
      if (this.timeInterval) return
      this.time = val
      this.timeInterval = setInterval(() => {
        this.time--
        if (this.time <= 0) {
          this.clearTimeFlow()
        }
      }, 1000)
    },
    clearTimeFlow() {
      clearInterval(this.timeInterval)
      this.time = 0
      this.timeInterval = null
    },
    submit() {
      if (!this.btnStatus) {
        return
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.dataForm.companyAmount == '' || this.dataForm.needAmount == '') {
            this.$message.error("请填写金额");
            return;
          }

          if (this.dataForm.type == 1) {//1资产
            if (this.dataForm.needAmount > 1000) {
              this.$message.error("融资需求额度最多1000万");
              return;
            }
          } else {//2流水
            if (this.dataForm.needAmount > 500) {
              this.$message.error("融资需求额度最多500万");
              return;
            }
          }

          if (!this.xieyi) {
            this.$message.error("请阅读并勾选协议");
            return;
          }
          icbcFinanceSave(this.dataForm).then(res => {
            this.phoneForm.id = res
            this.phoneForm.companyName = this.dataForm.companyName
            this.bindUser()
          })
          .catch((err) => {
            console.log(err)
          })
        }
      })
    },
    submitCode() {
      if (this.phoneForm.phone.length > 0 && this.phoneForm.code.length > 0) {
        icbcFinanceCheckCode({
          phone: this.phoneForm.phone,
          code: this.phoneForm.code,
          id: this.phoneForm.id
        }).then(res => {
          let url = 'http://quickbuy.icbc.com.cn/icbc/msy/jumpPage?f=ICBCqr&x=1&t=2&p=41&i=f8dc03ad8981804ed675e758c5bc4e8c&n=&l=f6e695a93fb21a53a1b1ffd1bcdffc439e248e33ce135e6eeaf72a9077c17ed4&k=115282660|9560828'
          window.location.href = url
        })
        .catch((err) => {
          console.log(err)
        })
      } else {
        this.$message.error('请把内容填写完整')
      }
    },
    openXieYi() {
      this.$router.push({
    		path: "/protocol",
    		query: {
    		}
    	});
    },
    handleIdPic(url) {
      photoOcr({url: url, type: 3}).then(response => { 
        if (response && response.companyName) {
          this.$set(this.dataForm, "companyName", response.companyName)
        }
      }).catch(error => {
        console.log(error);
      })
    },
    startBtnTimeGoing() {
      if (this.btnTime == 10) {
        if (this.btnInterval) return

        this.btnTitle = this.btnTime + 's'
        this.btnInterval = setInterval(() => {
          this.btnTime--
          this.btnTitle = this.btnTime + 's'
          if (this.btnTime <= 0) {
            this.btnTitle = '下一步'
            this.btnStatus = true
            this.clearBtnTimeFlow()
          }
        }, 1000)
      }
    },
    clearBtnTimeFlow() {
      clearInterval(this.btnInterval)
      this.btnTime = 0
      this.btnInterval = null
    },
    bindUser() {
      icbcFinanceBind(
        { id: this.phoneForm.id,
          phone: this.phoneForm.phone
        })
      .then(res => {
        this.step = 2
      })
      .catch((err) => {
        console.log(err)
      })
    }
  },
  created() {
    this.phoneForm.phone = this.$route.query.phone
    this.dataForm.openId = this.$route.query.openId
    this.scanState = this.$route.query.scanState
    this.dataForm.type = this.$route.query.type

    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      this.isShowInfo = false;

      this.btnStatus = false
      this.btnTitle = '下一步'
    } else {
      this.isShowInfo = true;
    }
  },
  mounted() {
    
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
  .info_bg {
    padding-top: 35px;
    .info {
      position: relative;
      display: flex;
      justify-content: center;
      
      width: 100%;
    }

    .title {
      display: flex;
      justify-content: center;
      margin-top: 30px;
      width: 100%;
    }

    .tips {
      font-weight: 400;
      font-size: 20px;
      color: black;
    }
  }

  .btn_bg {
    position: relative;
    display: flex;
    justify-content: center;

    .next_btn {
      width: calc(100% - 50px);
      margin-bottom: 50px;
      height: 40px;
      border-radius: 5px;
      line-height: 40px;
      text-align: center;
      background: rgb(24, 144, 255);
      color: white;
    }
  }

  .flexInput {
    display: flex;

    .el-input {
      width: auto;
      flex: 1;
    }
  }

  .iframe {
    width: 100%;
    height: 100%;
  }
</style>